import  pymysql

class DBUtil(object):
    conn = None

    @classmethod
    def __get_conn(cls):
        if cls.conn is None:
            cls.conn = pymysql.connect(host='192.168.135.0',
                                       port=8008,
                                       user='root',
                                       password='123456',
                                       database='',
                                       charset='utf8')
        return cls.conn

    @classmethod
    def __close_conner(cls):
        if cls.conn is not None:
            cls.conn.close()
            cls.conn = None

    # 查询一条
    @classmethod
    def select_one(cls, sql):
        cursor = None
        res = None

        try:
            # 获取连接
            cls.conn = cls.__get_conn()
            # 获取游标
            cursor = cls.conn.cursor()
            # 执行 uid语句
            cursor.execute(sql)
            # 提取一条结果
            res = cursor.fetchone()

        except Exception as err:
            print('查询语句sql错误：', str(err))

        finally:
            # 关闭游标
            cursor.close()
            # 关闭连接
            cls.__close_conner()
            # 将执行的sql语句返回
            return res

    # 增删改
    @classmethod
    def uid_db(cls, sql):
        cursor = None
        res = None

        try:
            # 获取连接
            cls.conn = cls.__get_conn()
            # 获取游标
            cursor = cls.conn.cursor()
            # 执行 查询语句
            cursor.execute(sql)
            # 提交事务
            cls.conn.commit()

        except Exception as err:
            # 回滚事务
            cls.conn.rollback()
            print('增删改sql执行失败：', str(err))

        finally:
            # 关闭游标
            cursor.close()
            # 关闭连接
            cls.__close_conner()
            # 将执行的sql语句返回
            return res

if __name__ == "__main__":
    res1 = DBUtil.select_one('select*from t_book where id = 8;')
    print('查询结果为：',res1)

    res2 = DBUtil.uid_db('updata t_book set is_delete = 1 where id 1111;')
    print('查询结果为：', res2)